package com.jt.common.service;

import com.jt.common.cache.LruTTLCache;
import com.jt.common.cache.LruTTLCacheManger;
import com.jt.common.config.MsConfigProperties;
import com.jt.common.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CacheServiceImpl implements CacheService {

    private final static Logger logger = LoggerFactory.getLogger(CacheServiceImpl.class);

    private LruTTLCache lruTTLCache = LruTTLCacheManger.getLruCacheInstance();

    @Autowired
    private MsConfigProperties msConfigProperties;

    @Autowired
    private RedisService redisService;

    @Override
    public void set(String key, Object object) {
        if (key == null) {
            return;
        }
        lruTTLCache.put(key,object);
        redisService.set(key, object);
    }

    @Override
    public void set(String key, Object object, long expire) {
        if (key == null || !msConfigProperties.isCacheEnabled()) {//如果缓存开关关闭不走缓存
            return;
        }
        lruTTLCache.put(key,object,expire);
        redisService.set(key, object,expire);
    }

    @Override
    public Object get(String key) {
        Object value = lruTTLCache.get(key);
        if(value != null) {
            logger.info("aop end,get result from jvmcache,key={},value={}",key,value);
            return value;
        }
        value = redisService.get(key);
        if(value != null){
            logger.info("aop end,get result from redis,key={},value={}",key,value);
        }
        return value;
    }

    @Override
    public void remove(String key) {
        redisService.delete(key);
        lruTTLCache.remove(key);
    }
}
